{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Neeps - Resit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading spark-stubs, spark-hive\n",
      "Adding Hive conf dir /opt/hive/conf to classpath\n",
      "Creating SparkSession\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "SLF4J: No SLF4J providers were found.\n",
      "SLF4J: Defaulting to no-operation (NOP) logger implementation\n",
      "SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<a target=\"_blank\" href=\"http://jupyter:4040\">Spark UI</a>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36m$ivy.$                                  \n",
       "\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.log4j.{Level, Logger}\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.types._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.functions._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.expressions.Window\n",
       "\n",
       "\u001b[39m\n",
       "\u001b[36mspark\u001b[39m: \u001b[32mSparkSession\u001b[39m = org.apache.spark.sql.SparkSession@f8ba6d2"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import $ivy.`org.apache.spark::spark-sql:3.4.0`\n",
    "\n",
    "import org.apache.log4j.{Level, Logger}\n",
    "Logger.getLogger(\"org\").setLevel(Level.OFF)\n",
    "\n",
    "import org.apache.spark._\n",
    "import org.apache.spark.sql._\n",
    "import org.apache.spark.sql.types._\n",
    "import org.apache.spark.sql.functions._\n",
    "import org.apache.spark.sql.expressions.Window\n",
    "\n",
    "val spark = {\n",
    "    NotebookSparkSession.builder()\n",
    "    .progress(false)\n",
    "    .appName(\"app15-4\")\n",
    "    // .master(\"spark://192.168.31.31:7077\")\n",
    "    .master(\"local[*]\")\n",
    "    .config(\"spark.sql.warehouse.dir\", \n",
    "            \"hdfs://192.168.31.31:9000/user/hive/warehouse\") \n",
    "    .config(\"spark.cores.max\", \"4\") \n",
    "    .config(\"spark.executor.instances\", \"1\") \n",
    "    .config(\"spark.executor.cores\", \"2\") \n",
    "    .config(\"spark.executor.memory\", \"10g\") \n",
    "    .config(\"spark.shuffle.service.enabled\", \"false\") \n",
    "    .config(\"spark.dynamicAllocation.enabled\", \"false\") \n",
    "    .config(\"spark.sql.catalogImplementation\", \"hive\")\n",
    "    .config(\"spark.sql.repl.eagerEval.enabled\", \"true\")\n",
    "    .config(\"spark.driver.allowMultipleContexts\", \"true\")\n",
    "    .getOrCreate()\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36mspark.implicits._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36mspark.sqlContext.implicits._\n",
       "\u001b[39m\n",
       "defined \u001b[32mfunction\u001b[39m \u001b[36msc\u001b[39m\n",
       "\u001b[36mhiveCxt\u001b[39m: \u001b[32msql\u001b[39m.\u001b[32mhive\u001b[39m.\u001b[32mHiveContext\u001b[39m = org.apache.spark.sql.hive.HiveContext@602aa07d"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import spark.implicits._\n",
    "import spark.sqlContext.implicits._\n",
    "def sc = spark.sparkContext\n",
    "val hiveCxt = new org.apache.spark.sql.hive.HiveContext(sc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defined \u001b[32mclass\u001b[39m \u001b[36mRichDF\u001b[39m"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "// Credit to Aivean\n",
    "implicit class RichDF(val ds:DataFrame) {\n",
    "    def showHTML(limit: Int = 50, truncate: Int = 100) = {\n",
    "        import xml.Utility.escape\n",
    "        val data = ds.take(limit)\n",
    "        val header = ds.schema.fieldNames.toSeq        \n",
    "        val rows: Seq[Seq[String]] = data.map { row =>\n",
    "          row.toSeq.map {cell =>\n",
    "            val str = cell match {\n",
    "              case null => \"null\"\n",
    "              case binary: Array[Byte] => binary.map(\"%02X\".format(_)).mkString(\"[\", \" \", \"]\")\n",
    "              case array: Array[_] => array.mkString(\"[\", \", \", \"]\")\n",
    "              case seq: Seq[_] => seq.mkString(\"[\", \", \", \"]\")\n",
    "              case _ => cell.toString\n",
    "            }\n",
    "            if (truncate > 0 && str.length > truncate) {\n",
    "              // do not show ellipses for strings shorter than 4 characters.\n",
    "              if (truncate < 4) str.substring(0, truncate)\n",
    "              else str.substring(0, truncate - 3) + \"...\"\n",
    "            } else {\n",
    "              str\n",
    "            }\n",
    "          }: Seq[String]\n",
    "        }\n",
    "    publish.html(s\"\"\" <table>\n",
    "                <tr>\n",
    "                 ${header.map(h => s\"<th>${escape(h)}</th>\").mkString}\n",
    "                </tr>\n",
    "                ${rows.map {row =>\n",
    "                  s\"<tr>${row.map{c => s\"<td>${escape(c)}</td>\" }.mkString}</tr>\"\n",
    "                }.mkString}\n",
    "            </table>\n",
    "        \"\"\")\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[36mut_staff\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: string, name: string]\n",
       "\u001b[36mut_student\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: string, name: string ... 2 more fields]\n",
       "\u001b[36mut_event\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: string, modle: string ... 5 more fields]\n",
       "\u001b[36mut_room\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: string, name: string ... 2 more fields]\n",
       "\u001b[36mut_attends\u001b[39m: \u001b[32mDataFrame\u001b[39m = [student: string, event: string]\n",
       "\u001b[36mut_teaches\u001b[39m: \u001b[32mDataFrame\u001b[39m = [staff: string, event: string]\n",
       "\u001b[36mut_occurs\u001b[39m: \u001b[32mDataFrame\u001b[39m = [event: string, week: string]\n",
       "\u001b[36mut_modle\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: string, name: string]\n",
       "\u001b[36mut_week\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: string, wkstart: string]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "val ut_staff = hiveCxt.table(\"sqlzoo.ut_staff\")\n",
    "val ut_student = hiveCxt.table(\"sqlzoo.ut_student\")\n",
    "val ut_event = hiveCxt.table(\"sqlzoo.ut_event\")\n",
    "val ut_room = hiveCxt.table(\"sqlzoo.ut_room\")\n",
    "val ut_attends = hiveCxt.table(\"sqlzoo.ut_attends\")\n",
    "val ut_teaches = hiveCxt.table(\"sqlzoo.ut_teaches\")\n",
    "val ut_occurs = hiveCxt.table(\"sqlzoo.ut_occurs\")\n",
    "val ut_modle = hiveCxt.table(\"sqlzoo.ut_modle\")\n",
    "val ut_week = hiveCxt.table(\"sqlzoo.ut_week\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.\n",
    "**Give the day and the time of the event co72002.L01.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>dow</th><th>tod</th>\n",
       "                </tr>\n",
       "                <tr><td>Monday</td><td>10:00</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(ut_event.filter(ut_event(\"id\") === \"co72002.L01\")\n",
    " .select(\"dow\", \"tod\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.\n",
    "**For each event in module co72003 show the day, the time and the place.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>id</th><th>dow</th><th>tod</th><th>room</th>\n",
       "                </tr>\n",
       "                <tr><td>co72003.L01</td><td>Monday</td><td>14:00</td><td>cr.B12</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(ut_event.filter(ut_event(\"modle\") === \"co72003\")\n",
    " .select(\"id\", \"dow\", \"tod\", \"room\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.\n",
    "**List the id of the events taught by \"Chisholm, Ken\".**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>event</th>\n",
       "                </tr>\n",
       "                <tr><td>co22006.L01</td></tr><tr><td>co22006.L02</td></tr><tr><td>co22006.L03</td></tr><tr><td>co22006.T01</td></tr><tr><td>co22006.T02</td></tr><tr><td>co72013.L01</td></tr><tr><td>co72013.L02</td></tr><tr><td>co72013.T01</td></tr><tr><td>co72013.T02</td></tr><tr><td>co72013.T06</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(ut_event.withColumnRenamed(\"id\", \"event\")\n",
    " .join(ut_teaches, \"event\")\n",
    " .join(ut_staff.filter(ut_staff(\"name\") === \"Chisholm, Ken\")\n",
    "       .withColumnRenamed(\"id\", \"staff\"), \"staff\")\n",
    " .select(\"event\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.\n",
    "**List the staff who teach in cr.SMH.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>name</th>\n",
       "                </tr>\n",
       "                <tr><td>Barclay, Ken</td></tr><tr><td>Chisholm, Ken</td></tr><tr><td>Cumming, Andrew</td></tr><tr><td>Greig, Frank</td></tr><tr><td>Hastie, Colin</td></tr><tr><td>Jackson, Jim</td></tr><tr><td>Kemmer, Rob</td></tr><tr><td>Lawson, Alistair</td></tr><tr><td>Macaulay, Catriona</td></tr><tr><td>Maclean, Aileen</td></tr><tr><td>McEwan, Tom</td></tr><tr><td>Middleton, Steve</td></tr><tr><td>Smith, Ian</td></tr><tr><td>Smyth, Michael</td></tr><tr><td>Soutar, Alastair</td></tr><tr><td>Turner, Susan</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(ut_staff.withColumnRenamed(\"id\", \"staff\")\n",
    " .join(ut_teaches, \"staff\")\n",
    " .join(ut_event.filter(ut_event(\"room\") === \"cr.SMH\")\n",
    "        .withColumnRenamed(\"id\", \"event\"), \"event\")\n",
    " .select(\"name\")\n",
    " .distinct()\n",
    " .orderBy(\"name\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.\n",
    "**Show the total number of hours (over the whole semester) of classes for com.IS.a**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>hrs</th>\n",
       "                </tr>\n",
       "                <tr><td>60</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(ut_event.withColumnRenamed(\"id\", \"event\")\n",
    " .join(ut_occurs, \"event\")\n",
    " .join(ut_attends.filter(col(\"student\") === \"com.IS.a\"),\n",
    "       \"event\")\n",
    " .groupBy()\n",
    " .agg(sum(\"duration\").alias(\"hrs\"))\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "spark.stop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala",
   "language": "scala",
   "name": "scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".sc",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.12.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
